import defaultUrl from './../assets/red.jpg';

export default class RedPacket {
    constructor(options) {
        this.url = options.url || defaultUrl;
        this.width = options.width || '20vw';
        this.height = options.height || 'auto';
        // 生成一个0-4的随机整数.
        const random = Math.floor(Math.random() * 5);
        this.track = options.track ||  random * 20; 
        // 生成一个-360-360的随机整数. // 生成一个3-8的随机整数. 
        const random1 = Math.floor(Math.random() * 721) - 360;
        const random2 = Math.floor(Math.random() * 6) + 3;
        this.rotate = options.rotate || random1;
        this.duration = options.duration || random2;  

        this.callback = options.callback || function () { };
        this.parent = options.parent || document.body;
        this.create();
    }
    create( ) {
        const img = document.createElement('img');
        img.src = this.url;
        img.style.width = this.width;
        img.style.height = this.height;
        // border-radius: 10px;
        img.style.borderRadius = '10px';
        // position: absolute;
        img.style.position = 'absolute'; 
        // left: 80vw;
        img.style.left = this.track + 'vw';


        img.animate([
            { transform: 'translateY(0)' },
            { transform: `translateY(120vh) rotate(${this.rotate}deg)` }
        ], {
            duration: this.duration * 1000,
            iterations: 1,
            fill: 'forwards'
        });  

   
        img.ontouchstart = this.destroy.bind(this, img);
        this.parent.appendChild(img);
        setTimeout(() => {
            img.remove();
        }, this.duration * 1000);
    }
    destroy (currentImg) {
        currentImg.remove();
        this.callback();
    }
}